package cc.miwuya.owner.controller;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.common.util.Result;
import cc.miwuya.core.BaseController;
import cc.miwuya.owner.domain.Orders;
import cc.miwuya.owner.service.OrdersService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Optional;

/**
 * @Author 迷雾森林
 * @Date 2024-04-15 17:08
 */
@RestController
@RequestMapping("/owner/order")
public class OrderController extends BaseController {
    @Resource
    OrdersService ordersService;
    @Resource
    HttpServletRequest httpServletRequest;

    @PostMapping("/addOrder")
    public void addOrder(@RequestBody Orders order) {
        ordersService.save(order);
    }

    @GetMapping("/deleteOrder/{id}")
    public void deleteOrder(@PathVariable Long id) {
        ordersService.removeById(id);
    }

    @GetMapping("/list")
    public Result list(String name) {
        return Result.success(ordersService.getPage(getPage(), name, getCurrent()));
    }

    @GetMapping("/getTollManOrderList")
    public Object getTollManOrderList(String name, Long TollManId) {
        return ordersService.getTollManOrderList(getPage(), name, TollManId);
    }

    /**
     * 获取当前登录人的身份
     *
     * @return
     */
    public Long getCurrent() {
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        System.out.println(parse);
        Long username = Long.parseLong(parse.getByPath("userId").toString());
        return username;
    }

    @GetMapping("/createOrder")
    public Result createOrder(Integer orderId) {
        Orders orders = ordersService.getById(orderId);
        orders.setOutOrderId(generateOrderSn());
        orders.setStatus(1);
        ordersService.saveOrUpdate(orders);
        return Result.success();
    }

    @GetMapping("/payOrder")
    public Result payOrder(Long orderId) {
        String header = httpServletRequest.getHeader("User-Agent");
        System.out.println(header);
        Optional<String> userAgentOptional = Optional.ofNullable(header);
        Object pay;
        if (userAgentOptional.isPresent() && (userAgentOptional.get().contains("Mobi") || userAgentOptional.get().contains("Android"))) {
            pay = ordersService.pay(orderId, "APP");
        } else {
            pay = ordersService.pay(orderId, "PC");
        }

        return Result.success(pay);
    }

    @GetMapping("/payCheck")
    public Result payCheck(Long orderId) {
        ordersService.payCheck(orderId);
        return Result.success();
    }

    public String generateOrderSn() {
        return DateUtil.format(new Date(), "yyMMddHHmmSS");
    }
}
